import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/Login.vue'
import ProfileView from '../views/ProfileView.vue'
import RechargeView from '../views/RechargeView.vue'
import LifecycleDemo from '../components/LifecycleDemo.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/music',
      name: 'music',
      component: () => import('../views/MusicHomeView.vue'),
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      meta: {
        requiresAuth: false
      }
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/recharge',
      name: 'recharge',
      component: RechargeView,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/lifecycle',
      name: 'lifecycle',
      component: LifecycleDemo,
      meta: {
        requiresAuth: false
      }
    },
  ],
})

// 全局前置守卫，用于处理登录验证
router.beforeEach((to, from, next) => {
  // 检查路由是否需要验证
  if (to.meta.requiresAuth) {
    // 模拟检查用户是否已登录
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
    
    if (isLoggedIn) {
      next();
    } else {
      // 未登录，重定向到登录页面
      next('/login');
    }
  } else {
    next();
  }
})

export default router
